﻿using RpcClient.Interface;
using RpcHelper;
using RpcHelper.Config;
using System.Collections.Generic;

namespace RpcClient.Config
{
    internal class RpcLogConfig : IRpcLogConfig
    {
        private static Dictionary<string, LocalLogSet> _defSet = new Dictionary<string, LocalLogSet>
        {
            {"ConfigRefresh", new LocalLogSet("Rpc_Config", LogGrade.Information)},
            {"RpcConLog", new LocalLogSet("Rpc_ConLog", LogGrade.Information)},
            {"RpcRouteErrorLog", new LocalLogSet("Rpc_RouteLog", LogGrade.WARN)},
            {"RpcRouteLog", new LocalLogSet("Rpc_RouteLog", LogGrade.DEBUG)},
            {"RpcMsg", new LocalLogSet("Rpc_Msg", LogGrade.DEBUG)},
            {"kafka", new LocalLogSet("Rpc_Kafka", LogGrade.DEBUG)},
            {"CentralMsg", new LocalLogSet("Rpc_CentralMsg", LogGrade.DEBUG)},
            {"RpcLog", new LocalLogSet("Rpc_Log", LogGrade.Information)},
            {"RpcNodeLog", new LocalLogSet("Rpc_Log", LogGrade.WARN)},
            {"RpcLocalError", new LocalLogSet("Rpc_Log", LogGrade.ERROR)},
        };
        private Dictionary<string, LocalLogSet> _LogSet;
        public RpcLogConfig(IConfigCollect config)
        {
            _LogSet = config.GetValue("rpc:RpcLog", _defSet);
            config.RefreshEvent += Config_RefreshEvent;
        }

        private void Config_RefreshEvent(IConfigCollect config, string name)
        {
            if (name == "rpc:RpcLog" || name.StartsWith("rpc:RpcLog:"))
            {
                _LogSet = config.GetValue("rpc:RpcLog", _defSet);
            }
        }

        public bool CheckIsRecord(string key, out LocalLogSet logSet)
        {
            if (_LogSet.TryGetValue(key, out logSet))
            {
                return LogSystem.CheckIsRecord(logSet.LogGrade);
            }
            return false;
        }
        public bool CheckIsRecord(string key, LogGrade grade, out LocalLogSet logSet)
        {
            if (_LogSet.TryGetValue(key, out logSet))
            {
                return LogSystem.CheckIsRecord(grade);
            }
            return false;
        }

        public bool CheckIsRecord(string key, ErrorException e, out LocalLogSet logSet)
        {
            if (_LogSet.TryGetValue(key, out logSet))
            {
                return LogSystem.CheckIsRecord(e);
            }
            return false;
        }
    }
    public class LocalLogSet
    {
        public LocalLogSet()
        {
        }
        public LocalLogSet(string group, LogGrade grade)
        {
            LogGroup = group;
            LogGrade = grade;
        }
        public string LogGroup { get; set; }

        public LogGrade LogGrade { get; set; }
    }
}
